package com.ruiysoft.aop;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.client.RedisConnectionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


@Aspect
@Component
@Order(30)
public class WebLogAspect {
    private static final Logger logger = LoggerFactory.getLogger(Thread.currentThread().getClass());

    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void pointcutRequestMapping() {
    }

    /**
     * 开始时间
     */
//    private long startTimeMillis = 0;
    /**
     * 结束时间
     */
//    private long endTimeMillis = 0;
    private Long getUserId() {
//        SysShopPersonnel personnel = LoginContextUtil.instance().getSysShopPersonnel();
//        return personnel.getId();
        return null;
    }

    private Long getShopId() {
//        SysMicroShop shop = LoginContextUtil.instance().getMicroShopLoginByPersonnelId();
//        return shop.getId();
        return null;
    }
    @Around("pointcutRequestMapping()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Long userId = getUserId();
        Long shopId = getShopId();
        //获取代理方法对象
        String targetName = pjp.getTarget().getClass().getName();
        String methodName = pjp.getSignature().getName();
        Object object = null;
//            logger.debug("-----------开始调用接口:[{}.{}],userId:[{}],shopId:[{}]----------", targetName, methodName, userId,shopId);
        long startTimeMillis = System.currentTimeMillis();
//        if(logger.isDebugEnabled()){

//            String startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startTimeMillis);
//            logger.debug("starttime:{}", startTime);
//        }
        Signature signature = pjp.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        String[] parameterNames = methodSignature.getParameterNames();
        Class[] parameterTypes = methodSignature.getParameterTypes();
        Object[] args = pjp.getArgs();
//            if (parameterNames != null && parameterNames.length > 0) {
//                int end = parameterNames.length;
        logger.info(logger.isDebugEnabled()+"-----------------------------");
        if(logger.isDebugEnabled()){
//            logger.debug("----api:[{}.{}]----{}" +
//                    "----userId:{}--shopId:{}----{}" +
//                    "----parameterName:{}--args:{}",
//                    targetName, methodName,System.getProperty("line.separator"),
//                    userId,shopId,System.getProperty("line.separator"),
//                    parameterNames,JSON.toJSONString(args));
            logger.debug("----api:[{}.{}]----{}" +
                            "----userId:{}--shopId:{}----{}" ,
                    targetName, methodName,System.getProperty("line.separator"),
                    userId,shopId,System.getProperty("line.separator")
                    );
        }

        try {
//                for (int i = 0; i < end; i++) {
//                    logger.debug("{} {}:[{}]",  parameterTypes[i].getSimpleName(), parameterNames[i], JSON.toJSONString(args[i]), true);
//                }
//            } else {
//                logger.debug("<<----开始打印 入参信息,接口:[{}.{}]----{}" +
//                        "----parameterName:{}--args:{}", targetName, methodName,System.getProperty("line.separator"),parameterNames,JSON.toJSONString(args));
//            }
            object = pjp.proceed();
            long endTimeMillis = System.currentTimeMillis();
            if(logger.isDebugEnabled()){
//                String endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTimeMillis);
//                logger.debug("endtime:{}", endTime);
                logger.debug("----apiResult[{}.{}],[{}]----{}----usetime:{}>>", targetName, methodName, JSON.toJSONString(object),System.getProperty("line.separator"),endTimeMillis - startTimeMillis);
            }

        } catch (Throwable e) {
//            logger.error("AOP 日志 捕捉到异常");
            logger.error("<<!!----error api:[{}.{}]----{}" +
                            "----userId:{}--shopId:{}----{}",
                    targetName, methodName,System.getProperty("line.separator"),
                    userId,shopId,System.getProperty("line.separator"),e);
            // throwable.printStackTrace();
            throw e;
        }
        return object;
    }


    private HttpServletRequest getHttpServletRequest() {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        return request;
    }
}
